package cn.itcast.gateway.filter;

import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.util.MultiValueMap;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

@Order(1)
@Component
public class AuthorizeFilter implements GlobalFilter {
    /**
     * 当前路由器的过滤器、DefaultFilter、GlobalFilter
     * 当前路由器的过滤器、DefaultFilter: order由Spring指定，按照声明顺序，由1递增
     * 过滤器执行顺序：DefaultFilter> 路由器的过滤器 > GlobalFilter
     */
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        // 1.获取请求参数
        MultiValueMap<String, String> queryParams = exchange.getRequest().getQueryParams();
        String authorization = queryParams.getFirst("authorization");
        // 2.判断
        //if ("admin".equals(authorization)) {
            // 2.1 放行
            return chain.filter(exchange);
        //}
        // 2.2 拦截
        // 2.2.1 设置状态码
        //exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED);
        // 2.2.2 结束请求
        //return exchange.getResponse().setComplete();
    }
}
